import {post} from "./Http";
import dayjs from "dayjs";

// //获取设备模块列表
// export const getModuleList = params => post('/api/v1/module/list', params);
// //获取设备模块状态
// export const getModuleStatus = params => post('/api/v1/module/status/get', params);
// //获取总产量
// export const getTotalOutput = params => post('/api/v1/statistics/output/total', params);
// //清零总产量
// export const clearTotalOutput = params => post('/api/v1/statistics/output/total/clear', params);
// //查询质量统计数据
// export const getMassStatistics = params => post('/api/v1/statistics/mass/get', params);
// //查询生产效率
// export const getDateOutputStatistics = params => post('/api/v1/statistics/output/date/get', params);
// //产品追溯
// export const getRecordLifecycle = params => post('/api/v1/record/lifecycle/get', params);
// //报表
// export const getReportData = params => post('/api/v1/reports', params);
// //查询产品记录
// export const getRecords = params => post('/api/v1/record/list', params);

//获取设备模块列表
export function getModuleList(params) {
  return new Promise((resolve, reject) => {
    resolve(getTestSuccessResult({
      modules: moduleList
    }));
  })
}
//获取设备模块状态
export function getModuleStatus(params) {
  return new Promise((resolve, reject) => {
    let moduleStatusList = [];
    if (!params.ids || params.ids.length < 1) {
      // 全部
      moduleList.forEach(function (item) {
        moduleStatusList.push({
          id: item.id,
          type: item.type,
          winder: item.type == 1 ? getRandomDetailInfo(item.id, item.type) : null,
          welder: item.type == 2 ? getRandomDetailInfo(item.id, item.type) : null,
          cutter: item.type == 3 ? getRandomDetailInfo(item.id, item.type) : null,
          powerOn: item.type == 4 ? getRandomDetailInfo(item.id, item.type) : null,
          tester: item.type == 5 ? getRandomDetailInfo(item.id, item.type) : null,
          blanker: item.type == 6 ? getRandomDetailInfo(item.id, item.type) : null
        })
      })
    } else {
      for (let i = 0; i < params.ids.length; i++) {
        let moduleInfo = getModuleById(params.ids[i]);
        if (moduleInfo) {
          moduleStatusList.push({
            id: moduleInfo.id,
            type: moduleInfo.type,
            winder: moduleInfo.type == 1 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null,
            welder: moduleInfo.type == 2 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null,
            cutter: moduleInfo.type == 3 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null,
            powerOn: moduleInfo.type == 4 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null,
            tester: moduleInfo.type == 5 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null,
            blanker: moduleInfo.type == 6 ? getRandomDetailInfo(moduleInfo.id, moduleInfo.type) : null
          })
        }
      }
    }
    resolve(getTestSuccessResult({
      moduleStatuss: moduleStatusList
    }));
  })
}
//获取总产量
export function getTotalOutput(params) {
  return new Promise((resolve, reject) => {
    resolve(getTestSuccessResult({
      output: getRandomIntInclusive(1000, 59999)
    }));
  })
}
//清零总产量
export function clearTotalOutput(params) {
  return new Promise((resolve, reject) => {
    resolve(getTestSuccessResult({}));
  })
}
//查询质量统计数据
export function getMassStatistics(params) {
  return new Promise((resolve, reject) => {
    resolve(getTestSuccessResult({
      ok: getRandomIntInclusive(1000, 10000),
      ng: getRandomIntInclusive(1000, 10000),
      na: getRandomIntInclusive(1000, 10000)
    }));
  })
}
//查询生产效率
export function getDateOutputStatistics(params) {
  return new Promise((resolve, reject) => {
    let days = getPastDays(params.n);
    let dateOutput = [];
    for (let i = 0; i < days.length; i++) {
      dateOutput.push({
        date: days[i],
        output: getRandomIntInclusive(10,50)
      });
    }
    resolve(getTestSuccessResult({
      dateOutput: dateOutput
    }));
  })
}
//产品追溯
export function getRecordLifecycle(params) {
  return new Promise((resolve, reject) => {
    let lifeCycles = [];
    for (let i = 0; i < params.codes.length; i++) {
      let dates = generateRandomTimes("2023-10-10 00:00:00", "2023-10-15 23:59:59", 6)
      let moduleCycles = [];
      dates.forEach(function (item) {
        let moduleInfo = moduleList[getRandomIntInclusive(0,9)]
        moduleCycles.push({
          id: moduleInfo.id,
          name: moduleInfo.name,
          type: moduleInfo.type,
          beginTime: item,
          endTime: item
        })
      })
      lifeCycles.push({
        code: params.codes[i],
        moduleCycles: moduleCycles,
        status: getRandomIntInclusive(1, 2)
      })
    }
    resolve(getTestSuccessResult({
      lifeCycles: lifeCycles
    }));
  })
}

export function getReportData(params) {
  return new Promise((resolve, reject) => {
    let reports = [];
    let dates = [];
    if (params.type == 1) {
      dates = getRangeDays(params.beginTime, params.endTime);
    } else if (params.type == 2) {
      dates = getRangeMonths(params.beginTime, params.endTime);
    } else {
      dates = getRangeYears(params.beginTime, params.endTime);
    }
    for (let i = 0; i < dates.length; i++) {
      let data = [];
      moduleList.forEach(function (item) {
        let d = {
          id: item.id,
          output: getRandomIntInclusive(10, 50000)
        };
        if (item.type == 4) {
          d.ok = getRandomIntInclusive(10,1000),
          d.ng = getRandomIntInclusive(10,1000)
        }
        data.push(d);
      });
      let ok = getRandomIntInclusive(10,1000);
      let ng = getRandomIntInclusive(10,1000);
      let na = getRandomIntInclusive(10,1000);
      let output = ok + ng + na;
      data.push({
        id: "-1",
        output: output,
        ok: ok,
        ng: ng,
        na: na
      })
      reports.push({
        date: dates[i],
        data: data
      })
    }
    resolve(getTestSuccessResult({
      reports: reports
    }));
  })
}

export function getRecords(params) {
  return new Promise((resolve, reject) => {
    let total = (params.pageNum + 5) * params.pageSize;
    let records = [];
    for (let i = 0; i < params.pageSize; i++) {
      records.push({
        code: generateRandomLetterString(10),
        beginTime: null,
        endTime: null
      })
    }
    resolve(getTestSuccessResult({
      total: total,
      records: records
    }));
  })
}


export const moduleList = [
  {id: "1", name: "1#绕线机", type: 1, describe: "", properties: null},
  {id: "2", name: "2#绕线机", type: 1, describe: "", properties: null},
  {id: "3", name: "3#绕线机", type: 1, describe: "", properties: null},
  {id: "4", name: "4#绕线机", type: 1, describe: "", properties: null},
  {id: "5", name: "5#绕线机", type: 1, describe: "", properties: null},
  {id: "6", name: "焊接机", type: 2, describe: "", properties: null},
  {id: "7", name: "切线机", type: 3, describe: "", properties: null},
  {id: "8", name: "通电测试", type: 4, describe: "", properties: null},
  {id: "9", name: "检测", type: 5, describe: "", properties: null},
  {id: "10", name: "下料", type: 6, describe: "", properties: null},
]

export function getModuleById(id) {
  for (let i = 0; i < moduleList.length; i++) {
    if (moduleList[i].id == id) {
      return moduleList[i];
    }
  }
  return null;
}

export function getTestSuccessResult(data) {
  return {code: 0, msg: "success", data: data}
}

export function getRandomDetailInfo(id, type) {
  //1 绕线机 2 焊接机 3 切线机 4 通电机 5 检测机 6 下料机
  if (type == 1) {
    return {
      id: id,
      mode: getRandomIntInclusive(1,2),
      totalOutput: getRandomIntInclusive(1000,10000),
      leftAxis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        thick: randomRangeNum(1, 20,2).toString(),
        diameter: randomRangeNum(1, 20,2).toString(),
        turns: randomRangeNum(1, 20,2).toString(),
        output: getRandomIntInclusive(10,500)
      },
      rightAxis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        thick: randomRangeNum(1, 20,2).toString(),
        diameter: randomRangeNum(1, 20,2).toString(),
        turns: randomRangeNum(1, 20,2).toString(),
        output: getRandomIntInclusive(10,500)
      }
    };
  } else if (type == 2) {
    return {
      id: id,
      oneAxis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000)
      },
      twoAxis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000)
      }
    };
  } else if (type == 3) {
    return {
      id: id,
      axis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000),
        status: getRandomIntInclusive(0, 1),
      },
      detail: {
        a: randomRangeNum(1, 20,2).toString(),
        b: randomRangeNum(1, 20,2).toString(),
        c: randomRangeNum(1, 20,2).toString(),
        d: randomRangeNum(1, 20,2).toString(),
        e: randomRangeNum(1, 20,2).toString(),
        f: randomRangeNum(1, 20,2).toString(),
      }
    };
  } else if (type == 4) {
    return {
      id: id,
      axis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000),
        status: getRandomIntInclusive(0, 1),
        ok: getRandomIntInclusive(1,2000),
        ng: getRandomIntInclusive(1,2000),
      },
      detail: {
        a: randomRangeNum(1, 20,2).toString(),
        b: randomRangeNum(1, 20,2).toString(),
        c: randomRangeNum(1, 20,2).toString(),
        d: randomRangeNum(1, 20,2).toString(),
        e: randomRangeNum(1, 20,2).toString(),
        f: randomRangeNum(1, 20,2).toString(),
        uv: randomRangeNum(1, 20,2).toString(),
        uw: randomRangeNum(1, 20,2).toString(),
        vw: randomRangeNum(1, 20,2).toString(),
        uvw: randomRangeNum(1, 20,2).toString()
      }
    };
  } else if (type == 5) {
    return {
      id: id,
      axis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000),
        status: getRandomIntInclusive(0, 1)
      },
      detail: {
        a: getRandomIntInclusive(0, 1).toString(),
        b: getRandomIntInclusive(0, 1).toString(),
        c: getRandomIntInclusive(0, 1).toString(),
        d: getRandomIntInclusive(0, 1).toString(),
        e: getRandomIntInclusive(0, 1).toString(),
        f: getRandomIntInclusive(0, 1).toString()
      }
    };
  } else if (type == 6) {
    return {
      id: id,
      axis: {
        mid: generateRandomLetterString(5),
        code: generateRandomLetterString(10),
        output: getRandomIntInclusive(1,2000),
        ok: getRandomIntInclusive(1,2000),
        ng: getRandomIntInclusive(1,2000),
        status: getRandomIntInclusive(0, 1)
      }
    };
  }
  return null;
}

export function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

export function generateRandomLetterString(length) {
  let result = '';
  // let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  let characters = '0123456789';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

export function randomRangeNum(maxNum, minNum, decimalNum) {
  let max = 0, min = 0;
  minNum <= maxNum ? (min = minNum, max = maxNum) : (min = maxNum, max = minNum);
  switch (arguments.length) {
    case 1:
      return Math.floor(Math.random() * (max + 1));
      break;
    case 2:
      return Math.floor(Math.random() * (max - min + 1) + min);
      break;
    case 3:
      return (Math.random() * (max - min) + min).toFixed(decimalNum);
      break;
    default:
      return Math.random();
      break;
  }
}

export function getPastDays(n) {
  let days = [];
  for (let i = 0; i < n; i++) {
    let date = new Date();
    date.setDate(date.getDate() - i); // 减去i天
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
    let day = String(date.getDate()).padStart(2, '0');
    days.push(`${year}-${month}-${day}`);
  }
  return days;
}

export function generateRandomTimes(startTime, endTime, count) {
  // 确保开始时间小于结束时间
  if (startTime > endTime) {
    [startTime, endTime] = [endTime, startTime];
  }

  // 将字符串转换为Date对象
  const startDate = new Date(startTime);
  const endDate = new Date(endTime);
  const timeDiff = endDate.getTime() - startDate.getTime();
  const randomTimes = [];

  // 生成随机时间并添加到数组中
  for (let i = 0; i < count; i++) {
    const randomTime = new Date(startDate.getTime() + Math.random() * timeDiff);
    randomTimes.push(randomTime);
  }

  // 对数组中的时间进行排序
  randomTimes.sort((a, b) => a - b);

  // 将Date对象转换为所需格式的字符串数组
  return randomTimes.map(time => time.toISOString().slice(0, 19)); // 'yyyy-MM-ddTHH:mm:ss' 格式，可根据需要调整格式
}

export function getRangeDays(startDay, endDay) {
  let startDate = dayjs(startDay);
  let endDate = dayjs(endDay);
  if (startDate.isAfter(endDate)) {
    [startDate, endDate] = [endDate, startDate];
  }
  let currentDate = startDate.clone(); // 克隆开始日期，以便在循环中修改
  let datesArray = []; // 存储所有日期的数组
  while (currentDate.isBefore(endDate)) {
    datesArray.push(currentDate.format('YYYY-MM-DD')); // 将当前日期添加到数组中
    currentDate = currentDate.add(1, 'day'); // 将当前日期增加一天
  }
  return datesArray;
}

export function getRangeMonths(startDay, endDay) {
  let startDate = dayjs(startDay);
  let endDate = dayjs(endDay);
  if (startDate.isAfter(endDate)) {
    [startDate, endDate] = [endDate, startDate];
  }
  // 创建一个空数组来存储结果
  const months = [];
  let currentDate = startDate.clone(); // 克隆startDate以避免修改原始日期
  while (currentDate.isBefore(endDate)) {
    // 获取当前日期的年份和月份，并以'yyyy-MM'的格式添加到数组中
    months.push(currentDate.format('YYYY-MM'));
    // 将当前日期设置为下一个月的第一天
    currentDate = currentDate.add(1, 'month').startOf('month'); // 设置为下一个月的第一天
  }
  return months;
}

export function getRangeYears(startDay, endDay) {
  let startDate = dayjs(startDay);
  let endDate = dayjs(endDay);
  if (startDate.isAfter(endDate)) {
    [startDate, endDate] = [endDate, startDate];
  }
  // 创建一个空数组来存储年份
  const years = [];
  let currentDate = startDate;
  while (currentDate.isBefore(endDate)) {
    // 添加当前日期的年份到数组中
    if (!years.includes(currentDate.year())) { // 确保年份不重复
      years.push(currentDate.year());
    }
    // 移动到下一天
    currentDate = currentDate.add(1, 'day');
  }
  return years;
}
